import { reactive, ref, computed } from 'vue';
import _ from 'lodash';
import { ElMessage } from "element-plus";
import * as Store from '@/store';
import Bus from '@/utils/bus';
import useUtils from './useUtils';
import useRight from './useRight';
import { delLesionData, delVideoGroup } from '@/api/readPathology/readPathology';
import type { HttpResponse } from "@/api/interceptor"
import type * as FilmReadStoreType from '@/store/modules/filmRead/type';

const leftHooksData = reactive({
  currentIndex: '',
  submenuVisibile: true,
  submenuTitleEyesVisibile: true,
  submenuEyesVisibile: true,
  menuItemVisibile: true,
  layerNum: 0,
  lesionNum: 0,
  popVisible: false,
  videoDisabled: false,
  isFrame: false
})
// 帧段选项卡状态值
const tabVal = ref(true)
const lesionItem = ref<any>({})

const useLeft = () => {
  const FilmRead = Store.useFilmRead();
  // 通过pinia数据集中解构出接口数据集合和字典数据集合
  const interfaceData = FilmRead.interfaceData
  const dictionaryData = FilmRead.dictionaryData
  const setLesionList = FilmRead.setLesionList
  
  // const {interfaceData,dictionaryData,setLesionList} = FilmRead
  /**
   * 左侧病灶列表/帧段列表标题点击事件
   * @param e 点击事件的event事件参数
   */
  const handleSubmenuClick = (e: MouseEvent) => {
    // 阻止事件冒泡
    e.stopPropagation();
    // 将聚焦的病灶项重置
    leftHooksData.currentIndex = '';
    // 将病灶列表/帧段列表标题名部分状态切换
    leftHooksData.submenuVisibile = !leftHooksData.submenuVisibile;
    // 将病灶列表/帧段列表下病灶状态的盒模型状态切换
    leftHooksData.menuItemVisibile = !leftHooksData.menuItemVisibile;
    lesionItem.value = {
      currentItem: null,
      id: leftHooksData.currentIndex
    }
    // 处理超声视频帧段列表下拉标题的交互
    dictionaryData.frameList && dictionaryData.frameList.map(item => {
      item.visibile = false;
    })
    // 将数据抛出
    Bus.emit("lesionClick", lesionItem.value);
  }

  /**
   * 左侧病灶列表/帧段列表标题眼睛状态切换事件
   * @param e 点击事件的event事件参数
   */
  const handleAllEyeClick = (e: MouseEvent, key?: number) => {
    // 阻止事件冒泡
    e.stopPropagation();
    if (!key) {
      // 将病灶列表/帧段列表标题的眼睛状态切换
      leftHooksData.submenuTitleEyesVisibile = !leftHooksData.submenuTitleEyesVisibile;
      // 处理超声视频帧段眼睛操作
      dictionaryData.frameList && dictionaryData.frameList.map(item => {
        item.eyeStatus = leftHooksData.submenuTitleEyesVisibile;
        item.visibile = false;
      })
      // 将病灶列表/帧段列表下的每一项眼睛状态切换
      dictionaryData.lesionDataList && Object.values(dictionaryData.lesionDataList).map(item => {
        if (Array.isArray(item)) {
          // 超声视频病灶眼睛处理及帧段眼睛处理
          // 多层数据结构，处理眼睛状态值
          item.map(it => {
            it.eyeStatus = leftHooksData.submenuTitleEyesVisibile;
          })
        } else {
          // 大图或者mpr处理病灶眼睛
          item.eyeStatus = leftHooksData.submenuTitleEyesVisibile;
        }
      })
    }
    
    if (key) {
      const tabCode = {
        1: "multi",
        2: "single"
      }
      lesionItem.value = {
        currentItem: dictionaryData.lesionDataList,
        type: 'all',
        isShowAll: leftHooksData.submenuTitleEyesVisibile,
        activeKey: tabCode[key]
      }
    } else {
      lesionItem.value = {
        currentItem: dictionaryData.lesionDataList,
        type: 'all',
        isShowAll: leftHooksData.submenuTitleEyesVisibile
      }
    }
    // 将数据抛出
    Bus.emit("lesionClick", lesionItem.value);
  }

  /**
   * 病灶列表/帧段列表眼睛点击事件
   * @param item 当前的病灶项/帧段项
   * @param e 事件参数
   */
  const handleLesionEyeClick = (item: FilmReadStoreType.LesionItem | FilmReadStoreType.LesionListItem, e: MouseEvent, flag: boolean = false, groupId?: number) => {
    // 阻止事件冒泡
    e.stopPropagation();
    lesionItem.value = {
      currentItem: item,
      type: 'eyes',
      id: +item.id,
      groupId
    }
    // 切换状态
    if ('eyeStatus' in item) {
      item.eyeStatus = !item.eyeStatus;
      lesionItem.value.isEyes = item.eyeStatus;
      // 超声模式下将帧段下所有病灶眼睛状态切换
      // item.lesionList && item.lesionList.length !== 0 && item.lesionList.map(it => it.itemEyeStatus = item.eyeStatus);
    }
    // 点击当前帧段下病灶
    // if('itemEyeStatus' in item) {
    //   item.itemEyeStatus = !item.itemEyeStatus;
    //   lesionItem.value.isEyes = item.itemEyeStatus;
    // }
    let itemEyes: boolean[] = [];
    if (dictionaryData.lesionDataList) {
      const layoutFlag = interfaceData.pageSettingList.imageLayout === "VIDEO_ANNO";
      // layoutFlag 为true 为超声视频
      // 根据flag判定超声视频时多帧还是单帧 flag为true则为多帧
      if (layoutFlag && flag) {
        // 获取当前病灶的眼睛
        const lesionEyes = Array.isArray(dictionaryData.lesionDataList[item.groupId]) && dictionaryData.lesionDataList[item.groupId].map(t => t.eyeStatus);
        const findLesionEyeItem = lesionEyes.find(t => t === true);
        // 通过获取的布尔值改变帧段集合数据的eyeStatus
        dictionaryData.frameList && dictionaryData.frameList.map(t => {
          findLesionEyeItem && t.id === +item.groupId && (t.eyeStatus = true);
          !findLesionEyeItem && t.id === +item.groupId && (t.eyeStatus = false);
        })
        // 控制当前帧段的眼睛
        dictionaryData.frameList && (itemEyes = dictionaryData.frameList.map(t => t.eyeStatus));
      }
      // flag 为 flase 为单帧
      // 此时为单帧标注所以直接获取lesionDataList字典中的key为0一项的value
      layoutFlag && !flag && Array.isArray(dictionaryData.lesionDataList[0]) && (itemEyes = dictionaryData.lesionDataList[0].map(t => t.eyeStatus));
      // layoutFlag 为false 为mpr或者大图
      // 大图和mpr处理
      !layoutFlag && (itemEyes = Object.values(dictionaryData.lesionDataList).map(item => !Array.isArray(item) && item.eyeStatus));
    }
    const findEyeItem = itemEyes?.find(item => item === true);
    !findEyeItem && (leftHooksData.submenuTitleEyesVisibile = false);
    findEyeItem && (leftHooksData.submenuTitleEyesVisibile = true);
    // 抛出事件
    Bus.emit("lesionClick", lesionItem.value);
  }

  /**
   * 超声视频模式下帧段标题点击事件
   * @param item 当前帧段点击的一项
   */
  const handleFrameClick = (item: FilmReadStoreType.LesionItem) => {
    // 帧段点击
    item.visibile = !item.visibile;
    // 将其他帧段状态重置
    dictionaryData.frameList && dictionaryData.frameList.map(it => {
      // item.visibile = false;
      if (it.id !== item.id) {
        it.visibile = false;
      }
    })
    // 选中当前帧段
    leftHooksData.currentIndex = item.id.toString();
    leftHooksData.isFrame = item.visibile
    if (!item.visibile) {
      leftHooksData.currentIndex = ""
    }
    lesionItem.value = {
      currentItem: item,
      type: 'frame',
      id: +item.id
    }
    Bus.emit("lesionClick", lesionItem.value)
  }

  /**
   * 超声视频模式下帧段眼睛点击事件
   * @param e 鼠标事件事件参数
   * @param item 当前帧段点击的一项
   */
  const handleFrameEyeClick = (e: MouseEvent, item: FilmReadStoreType.LesionItem) => {
    // 阻止事件冒泡
    e.stopPropagation();
    lesionItem.value = {
      currentItem: item,
      type: 'frameEyes',
      id: +item.id
    }
    // 改变当前眼睛状态
    item.eyeStatus = !item.eyeStatus;
    // 通过当前的状态改变下面病灶
    dictionaryData.lesionDataList && Array.isArray(dictionaryData.lesionDataList[item.id]) && (dictionaryData.lesionDataList[item.id] = dictionaryData.lesionDataList[item.id].map(t => {
      t.eyeStatus = item.eyeStatus
      return t;
    }));
    // 获取当前所有帧段眼睛状态集合
    const groupEyes = dictionaryData.frameList && dictionaryData.frameList.map(t => t.eyeStatus);
    const findEyeItem = groupEyes?.find(item => item === true);
    !findEyeItem && (leftHooksData.submenuTitleEyesVisibile = false);
    findEyeItem && (leftHooksData.submenuTitleEyesVisibile = true);
    // 抛出事件
    Bus.emit("lesionClick", lesionItem.value);
  }

  /**
   * 当前病灶名点击事件
   * @param item 当前病灶项/帧段下病灶项
   * @param e 事件参数
   */
  const handleLesionClick = (item: FilmReadStoreType.LesionItem | FilmReadStoreType.LesionListItem, groupId?: number) => {
    // 选中当前病灶
    lesionSetActive(item.id.toString());
    const result = dictionaryData && dictionaryData.imageDataList && dictionaryData.imageDataList[item.id]
    lesionItem.value = {
      currentItem: {...item, ...result},
      type: 'lesion',
      isLesion: leftHooksData.currentIndex,
      id: +item.id,
      groupId
    }
    leftHooksData.isFrame = false;
    // 抛出事件
    Bus.emit("lesionClick", lesionItem.value);
  }

  /**
   * 病灶列表下病灶颜色变更事件
   * @param item 当前病灶项
   * @param value 并更的颜色值
   */
  const handleColorChange = (item: FilmReadStoreType.LesionItem, value: string) => {
    lesionItem.value = {
      currentItem: item,
      value,
      type: 'color'
    }
    // 抛出事件
    Bus.emit("lesionClick", lesionItem.value);
  }

  /**
   * 病灶删除事件
   * @param item 当前病灶列表下病灶项/帧段列表下病灶项
   * @param e 事件参数
   */
  const handleDelClick = async (item: FilmReadStoreType.LesionItem | FilmReadStoreType.LesionListItem, e: MouseEvent, groupId?: number) => {
    // 阻止事件冒泡
    e.stopPropagation();
    lesionItem.value = {
      currentItem: item,
      id: item.id,
      type: 'del',
      groupId
    }
    // 创建删除操作
    const alrId = item.id;
    const res: any = await delLesionData(String(alrId));
    if (res.code === 200) {
      ElMessage.success('删除成功！');
      // lesionDel(item.id);
      // lesionSetActive(item.id.toString());
      // UtilsHooks.lesionEvent.lesionSetActive(item.id.toString());
      // 抛出事件
      Bus.emit("lesionClick", lesionItem.value);
    }
  }

  /**
   * 病灶列表数据增加方法
   * @param createObj 当前增加数据参数
   */
  const lesionAdd = (createObj: any) => {
    if (dictionaryData.lesionDataList) {
      if (interfaceData.pageSettingList.imageLayout === 'VIDEO_ANNO') {
        if (Array.isArray(dictionaryData.lesionDataList[createObj.groupId])) {
          const index = dictionaryData.lesionDataList[createObj.groupId].filter(item => !item.alg).length
          const element = dictionaryData.lesionDataList[createObj.groupId]
          let chunkArr = _.chunk(element as FilmReadStoreType.LesionItem[], index)
          chunkArr.splice(1, 0, createObj)
          let res = _.flatten(chunkArr)
          dictionaryData.lesionDataList[createObj.groupId] = res;
          // dictionaryData.lesionDataList[createObj.groupId].push(createObj)
          setLesionList(dictionaryData.lesionDataList)
        }
      } else {
        dictionaryData.lesionDataList[createObj.id] = createObj;
      }
    }
  }

  /**
   * 删除病灶方法
   * @param lesionId 当前病灶id
   * @param frameId 当前帧段id
   */
  const lesionDel = (lesionId: number, frameId?: number) => {
    // lesionSetActive(lesionId.toString());
    // 区分超声视频删除病灶还是其他模式删除病灶
    if (dictionaryData.lesionDataList) {
      if (interfaceData.pageSettingList.imageLayout === 'VIDEO_ANNO') {
        if (frameId && Array.isArray(dictionaryData.lesionDataList[frameId])) {
          dictionaryData.lesionDataList[frameId] = dictionaryData.lesionDataList[frameId].filter(item => item.id !== lesionId);
        } else {
          dictionaryData.lesionDataList[0] = dictionaryData.lesionDataList[0].filter(item => item.id !== lesionId);
        }
      } else {
        // 删除选中病灶和删除未选中病灶逻辑
        delete dictionaryData.lesionDataList[lesionId];
      }
    }
    // if (dictionaryData.lesionDataList) {
    //   if (type && type === "multi") { 
    //     // 视频多帧
    //     // 删除当前帧段下的所有病灶
    //     if (Array.isArray(dictionaryData.lesionDataList[lesionId])) {
    //       delete dictionaryData.lesionDataList[lesionId];
    //     }
    //   } else {
    //     // 删除选中病灶和删除未选中病灶逻辑
    //     delete dictionaryData.lesionDataList[lesionId];
    //   }
    // }
  }

  /**
   * 聚焦当前病灶或反选
   * @param lesionId 当前病灶id
   */
  const lesionSetActive = (lesionId: string) => {
    if (leftHooksData.currentIndex === lesionId) {
      leftHooksData.currentIndex = '';
    } else {
      leftHooksData.currentIndex = lesionId;
    }
    // RightHooks.seriesChangeActive(+leftHooksData.currentIndex);
    // UtilsHooks.seriesEvent.seriesChangeActive(+leftHooksData.currentIndex);
  }
  const setLesionActive = (lesionId: string) => {
    leftHooksData.currentIndex = lesionId;
  }

  /**
   * 移除当前病灶
   */
  const lesionRemoveActive = () => {
    leftHooksData.currentIndex = '';
  }
  let tempE: MouseEvent;
  const handlePopConfirmClick = (e: MouseEvent) => {
    leftHooksData.popVisible = true;
    tempE = e;
  }

  const handleSecondClick = (item: FilmReadStoreType.LesionItem | FilmReadStoreType.LesionListItem, groupId?: number) => {
    handleDelClick(item, tempE, groupId)
  }

  const resetHookData = () => {
    leftHooksData.currentIndex = '';
    leftHooksData.submenuVisibile = true;
    leftHooksData.submenuTitleEyesVisibile = true;
    leftHooksData.submenuEyesVisibile = true;
    leftHooksData.menuItemVisibile = true;
    leftHooksData.layerNum = 0;
    leftHooksData.lesionNum = 0;
    leftHooksData.popVisible = false;
    leftHooksData.isFrame = false;
    if (interfaceData.pageSettingList.imageLayout === "VIDEO_ANNO") {
      const UtilsHooks = useUtils()
      UtilsHooks.seriesEvent.seriesChangeActive()
    }
    // 获取病灶总条数
    // if (
    //   dictionaryData.lesionDataList &&
    //   Object.keys(dictionaryData.lesionDataList).length !== 0
    // ) {
    //   leftHooksData.lesionNum = Object.keys(
    //     dictionaryData.lesionDataList
    //   ).length;
    // }
  }

  // 超声视频删除帧段
  const handleFrameDelClick = async (item: FilmReadStoreType.LesionItem | FilmReadStoreType.LesionListItem) => {
    lesionItem.value = {
      currentItem: item,
      id: item.id,
      type: 'delFrame'
    }
    const res: any = await delVideoGroup(item.id)
    console.log(res, "删除帧段");
    if (res.code === 200) {
      ElMessage.success('删除成功！');
      // lesionDel(item.id);
      // lesionSetActive(item.id.toString());
      // UtilsHooks.lesionEvent.lesionSetActive(item.id.toString());
      // frameDel(item.id)
      // 抛出事件
      Bus.emit("lesionClick", lesionItem.value);
    }
  }

  /**
   * 病灶列表帧段数据增加方法
   * @param createObj 当前增加数据参数
   */
  const frameAdd = (createObj: any) => {
    // dictionaryData.lesionDataList && (dictionaryData.lesionDataList[createObj.id] = createObj);
    // 针对帧段追加数据
    dictionaryData.frameList && (dictionaryData.frameList.push(createObj))
    // 帧段当前帧段id判断病灶集合是否存在并初始化数据
    dictionaryData.lesionDataList && !dictionaryData.lesionDataList[createObj.id] && (dictionaryData.lesionDataList[createObj.id] = []);
    //高亮
    dictionaryData.frameList && dictionaryData.frameList.map(item => {
      item.visibile = (item.id === createObj.id)
    })
  }

  /**
   * 删除帧段方法
   * @param frameId 当前帧段组id
   */
  const frameDel = (frameId: number) => {
    // lesionSetActive(lesionId.toString());
    // 删除帧段数据集合中的帧段数据
    if (dictionaryData.frameList) {
      dictionaryData.frameList = dictionaryData.frameList.filter(item => item.id !== frameId);
    }
    // 删除当前删除帧段下的病灶数据
    if (dictionaryData.lesionDataList) {
      delete dictionaryData.lesionDataList[frameId]
    }
  }
  
  /**
   * 更新帧段方法
   * @param updateObj 帧段更新数据
   */
  const frameUpdate = (updateObj: {id: number, info: { startFrame: number; endFrame: number; } }) => {
    const { id, info } = updateObj
    dictionaryData.frameList && (dictionaryData.frameList = dictionaryData.frameList.map(item => {
      if (item.id === id) {
        item.info = {
          ...item.info,
          ...info
        }
      }
      return item
    }))
  }

  /**
   * 聚焦当前帧段方法
   * @param frameId 帧段组id
   */
  const frameActive = (frameId: number) => {
    setActiveTabValue(frameId)
    // dictionaryData.frameList && dictionaryData.frameList.map(item => item.visibile = false);
    dictionaryData.frameList && dictionaryData.frameList.map(item => {
      if (item.id === frameId) {
        item.visibile = true;
      } else {
        item.visibile = false;
      }
    })
  }

  /**
   * 设置当前hook中的帧段选项卡状态值方法
   * @param frameId 帧段组id
   */
  const setActiveTabValue = (frameId: number) => {
    tabVal.value = frameId !== 0
  }

  const setTabValue = (activeKey: number) => {
    tabVal.value = activeKey === 1
  }

  /**
   * 获取当前hook中的帧段选项卡值方法
   * @returns 当前帧段选项卡值
   */
  const getTabValue = () => tabVal

  return {
    leftHooksData,
    handleSubmenuClick,
    handleAllEyeClick,
    handleLesionEyeClick,
    handleLesionClick,
    handleColorChange,
    handleDelClick,
    handleFrameClick,
    lesionAdd,
    lesionDel,
    lesionSetActive,
    setLesionActive,
    lesionRemoveActive,
    handlePopConfirmClick,
    handleSecondClick,
    resetHookData,
    handleFrameDelClick,
    frameAdd,
    frameDel,
    frameUpdate,
    frameActive,
    handleFrameEyeClick,
    getTabValue,
    setTabValue
  }
};

export default useLeft;